<!--
 * @Author: Lw
 * @Date: 2022-09-05 11:24:20
 * @LastEditors: Lw
 * @LastEditTime: 2022-10-09 17:35:55
-->
<template>
  <Dialog v-model:show="show" :title="title" :maskClosable="!loading">
    <n-spin :show="loading">
      <n-space size="large" vertical>
        <Form
          ref="formRef"
          :options="options"
          :form="form"
          :rules="rules"
          :cols="cols"
          :onlyRead="onlyRead"
          @change="(params) => emit('change', params)"
        >
          <template #formItem="{ key, value }">
            <slot :key="key" :value="value"></slot>
          </template>
        </Form>
        <div v-if="onlyRead" style="height: 0px" />
        <n-space justify="end" v-if="!onlyRead">
          <n-button type="primary" size="large" secondary @click="handleCacel"> 取消 </n-button>
          <n-button type="primary" size="large" @click="handleOk">确认</n-button>
        </n-space>
      </n-space>
    </n-spin>
  </Dialog>
</template>

<script setup>
  import Dialog from '@/components/Dialog/index.vue'
  import Form from '@/components/Form/index.vue'

  const emit = defineEmits(['update:show', 'ok', 'change', 'cacel'])

  defineComponent({
    inheritAttrs: false,
  })

  const props = defineProps({
    loading: {
      type: Boolean,
      default: false,
    },
    show: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
    },
    options: {
      type: Array,
      required: true,
    },
    form: {
      type: Object,
      required: true,
    },
    rules: {
      type: Object,
      default: () => {},
    },
    cols: {
      type: Number,
      default: 2,
    },
    onlyRead: {
      type: Boolean,
    },
  })
  const formRef = ref()
  const show = computed({
    get: () => props.show,
    set: (val) => emit('update:show', val),
  })
  const handleOk = async () => {
    const res = await formRef.value.validate()
    if (res) {
      emit('ok')
    }
  }
  const handleCacel = () => {
    formRef.value.clearValidate()
    emit('update:show', false)
  }
  watch(
    () => props.show,
    (show) => {
      if (!show) {
        emit('update:show', show)
      }
    },
  )

  const change = () => {
    formRef.value.change()
  }
</script>

<style lang="scss" scoped></style>
